﻿using System;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Framework;
using ISSMoviePlex.ServiceClient.AccountServiceReference;
using ISSMoviePlex.ServiceClient.MovieServiceReference;
using ISSMoviePlex.ServiceClient.TicketBookingServiceReference;

namespace ISSMoviePlex.ServiceClient
{
    class Program
    {
        private static string cookie;

        private static void Main(string[] args)
        {
            var accountService = new AccountServiceClient();
            var movieService = new MovieServiceClient();
            var ticketBookingService = new TicketBookingServiceClient();

            var movieServiceOnShowing = true;
            var ticketServiceOnShowing = true;
            var shouldShowMenu = true;



            _.L(3, "START CLIENT");
            _.P("Welcome to ISSCinePlex Service Client Demo");
            _.P("In order to use our service, please login");
            Console.Write("Please enter your username: ");
            var userName = Console.ReadLine();
            Console.Write("Please enter your password: ");
            var password = Console.ReadLine();
            Console.Write("Do you want to remember (yes/no): ");
            var isRememberText = Console.ReadLine();

            var isRemember = isRememberText != null && isRememberText.Trim().ToLower().Equals("yes");
            var result = false;
            using (new OperationContextScope(accountService.InnerChannel))
            {
                try
                {
                    result = accountService.AuthorizeUser(password, userName, isRemember, AccountBLLRole.Admin);
                    var responseMessageProperty = (HttpResponseMessageProperty)
                         OperationContext.Current.IncomingMessageProperties[HttpResponseMessageProperty.Name];

                    if (result)
                    {
                        cookie = responseMessageProperty.Headers.Get("Set-Cookie");
                        _.P("Saved to cookie: User={0}".FormatWith(userName));
                        _.P("Cookie: {0}".FormatWith(cookie));
                    }
                }
                catch (FaultException<AuthorizationFault> e)
                {
                    Console.WriteLine("FaultException<AuthorizationFault>: Authorization fault while doing " +
                                        e.Detail.Operation + ". Problem: " + e.Detail.ProblemType);
                    Console.ReadKey();
                }
            }
            Console.ReadKey();
            _.P("Enter to continue");

            if (result && Is.NotEmptyString(cookie))
            {
                while (shouldShowMenu)
                {
                    Console.Clear();
                    _.L(3, "Service available");
                    _.P("1. Movie Services");
                    _.P("2. Ticket Booking Services");
                    _.P("3. Exit");
                    Console.Write("Enter your choice: ");
                    try
                    {
                        var option = Convert.ToInt32(Console.ReadLine());
                        if (option == 1)
                        {
                            movieServiceOnShowing = true;
                            while (movieServiceOnShowing)
                            {
                                Console.Clear();
                                _.L(3, "Movie Service");
                                _.P("1. Get All Movies");
                                _.P("2. Search Movie By Title");
                                _.P("3. Search Movie By Genre");
                                _.P("4. Back To Menu");

                                Console.Write("Please enter your selection: ");
                                try
                                {
                                    var selection = Convert.ToInt32(Console.ReadLine());
                                    if (selection == 1)
                                    {
                                        Console.Clear();
                                        if (string.IsNullOrEmpty(cookie))
                                        {
                                            _.P("Please login first");
                                            Console.ReadKey();
                                            return;
                                        }

                                        using (new OperationContextScope(movieService.InnerChannel))
                                        {
                                            var request = new HttpRequestMessageProperty();
                                            request.Headers[HttpResponseHeader.SetCookie] = cookie;
                                            OperationContext.Current.OutgoingMessageProperties
                                                     [HttpRequestMessageProperty.Name] = request;

                                            try
                                            {
                                                var allMovies = movieService.GetAllMovies();
                                                PrintMovies(allMovies);
                                            }
                                            catch (FaultException<AuthorizationFault> e)
                                            {
                                                Console.WriteLine("FaultException<AuthorizationFault>: Authorization fault while doing " +
                                                e.Detail.Operation + ". Problem: " + e.Detail.ProblemType);
                                            }

                                            Console.Write("Press enter to back to menu");
                                            movieServiceOnShowing = false;
                                            var key = Console.ReadKey();
                                            if (key.Key.Equals(ConsoleKey.Enter))
                                            {
                                                movieServiceOnShowing = true;
                                            }
                                        }
                                    }
                                    else if (selection == 2)
                                    {
                                        if (string.IsNullOrEmpty(cookie))
                                        {
                                            _.P("Please login first");
                                            Console.ReadKey();
                                            return;
                                        }

                                        Console.Clear();
                                        Console.Write("Enter your Movie Title To Search: ");
                                        var title = Console.ReadLine();

                                        using (new OperationContextScope(movieService.InnerChannel))
                                        {
                                            var request = new HttpRequestMessageProperty();
                                            request.Headers[HttpResponseHeader.SetCookie] = cookie;
                                            OperationContext.Current.OutgoingMessageProperties
                                                [HttpRequestMessageProperty.Name] = request;

                                            try
                                            {
                                                PrintMovies(movieService.SearchMovieByTitle(title));
                                            }
                                            catch (FaultException<AuthorizationFault> e)
                                            {
                                                Console.WriteLine(
                                                    "FaultException<AuthorizationFault>: Authorization fault while doing " +
                                                    e.Detail.Operation + ". Problem: " + e.Detail.ProblemType);
                                            }
                                            Console.Write("Press enter to back to menu");
                                            movieServiceOnShowing = false;
                                            var key = Console.ReadKey();
                                            if (key.Key.Equals(ConsoleKey.Enter))
                                            {
                                                movieServiceOnShowing = true;
                                            }
                                        }
                                    }
                                    else if (selection == 3)
                                    {

                                        if (string.IsNullOrEmpty(cookie))
                                        {
                                            _.P("Please login first");
                                            Console.ReadKey();
                                            return;
                                        }

                                        Console.Clear();
                                        Console.Write("Enter your Genre To Search: ");
                                        var genre = Console.ReadLine();
                                        using (new OperationContextScope(movieService.InnerChannel))
                                        {
                                            var request = new HttpRequestMessageProperty();
                                            request.Headers[HttpResponseHeader.SetCookie] = cookie;
                                            OperationContext.Current.OutgoingMessageProperties
                                                [HttpRequestMessageProperty.Name] = request;

                                            try
                                            {
                                                PrintMovies(movieService.GetMovieByGenre(genre));
                                            }
                                            catch (FaultException<AuthorizationFault> e)
                                            {
                                                Console.WriteLine(
                                                    "FaultException<AuthorizationFault>: Authorization fault while doing " +
                                                    e.Detail.Operation + ". Problem: " + e.Detail.ProblemType);
                                            }
                                            Console.Write("Press enter to back to menu");
                                            movieServiceOnShowing = false;
                                            var key = Console.ReadKey();
                                            if (key.Key.Equals(ConsoleKey.Enter))
                                            {
                                                movieServiceOnShowing = true;
                                            }
                                        }
                                    }
                                    else if (selection == 4)
                                    {
                                        movieServiceOnShowing = false;
                                    }
                                }
                                catch (Exception e1)
                                {
                                    _.P(e1.Message);
                                    _.P("Error! Please enter valid number");
                                }
                            }
                        }
                        if (option == 2)
                        {
                            ticketServiceOnShowing = true;
                            while (ticketServiceOnShowing)
                            {
                                Console.Clear();
                                _.L(3, "Ticket Booking Service");
                                _.P("1. Get Shedule Of Movie");
                                _.P("2. Book Ticket");
                                _.P("3. Back To Menu");
                                try
                                {
                                    var selection = Convert.ToInt32(Console.ReadLine());
                                    if (selection == 1)
                                    {
                                        Console.Clear();
                                        Console.Write("Enter your Movie Title To Search: ");
                                        var title = Console.ReadLine();
                                        var allSchedules = ticketBookingService.GetSchedules(title);
                                        PrintSchedule(allSchedules);
                                        Console.Write("Press enter to back to menu");
                                        ticketServiceOnShowing = false;
                                        var key = Console.ReadKey();
                                        if (key.Key.Equals(ConsoleKey.Enter))
                                        {
                                            ticketServiceOnShowing = true;
                                        }
                                    }
                                    else if (selection == 2)
                                    {
                                        Console.Clear();
                                        try
                                        {
                                            Console.Write("Enter Member ID: ");
                                            var memberId = Convert.ToInt32(Console.ReadLine());
                                            Console.Write("Enter Schedule ID: ");
                                            var scheduleId = Convert.ToInt32(Console.ReadLine());
                                            Console.Write("Enter number of tickets: ");
                                            var numberOfTickets = Convert.ToInt32(Console.ReadLine());
                                            ticketBookingService.BookTicket(numberOfTickets, scheduleId, memberId);
                                            Console.WriteLine("Congratulations! Booked {0} tickets successfully.".FormatWith(numberOfTickets));
                                        }
                                        catch (Exception e2)
                                        {
                                            _.P("Please enter correct value");
                                        }

                                        Console.WriteLine("Press enter to back to menu");
                                        ticketServiceOnShowing = false;
                                        var key = Console.ReadKey();
                                        if (key.Key.Equals(ConsoleKey.Enter))
                                        {
                                            ticketServiceOnShowing = true;
                                        }
                                    }
                                    else if (selection == 3)
                                    {
                                        ticketServiceOnShowing = false;
                                    }
                                }
                                catch (Exception e1)
                                {
                                    _.P(e1.Message);
                                    _.P("Error! Please enter valid number");
                                }
                            }
                        }
                        if (option == 3)
                        {
                            shouldShowMenu = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        _.P(ex.Message);
                        _.P("Error! Please enter valid number");
                    }
                }
            }
        }

        /*
         * PRIVATE HELPER METHOD
         */
        private static void PrintSchedule(ScheduleCollection allSchedules)
        {
            for (var i = 1; i <= allSchedules.Count; i++)
            {
                var schedule = allSchedules[i - 1];
                _.P("{0}. ScheduleId={1} - MovieId={2} - ShowTime:{3} - Seat:{4}".FormatWith(i, schedule.ScheduleId, schedule.MovieId, schedule.ShowTime, schedule.SeatAvailable));
            }
        }


        private static void PrintMovies(MovieCollection movies)
        {
            for (var i = 1; i <= movies.Count; i++)
            {
                var movie = movies[i - 1];
                _.P("{0}. {1} - {2}".FormatWith(i, movie.MovieId, movie.MovieName));
            }
        }
    }
}

